
/**
 *
 */
package com.serviceprovider.business.module.admin.transaction.controller;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.transaction.model.NewCsvReplica;
import com.serviceprovider.business.module.admin.transaction.services.dao.interfaces.ITransactionImportDataService;
import com.serviceprovider.business.module.admin.transaction.services.dao.interfaces.IValidationService;
import com.serviceprovider.business.module.admin.transaction.utility.StringUtils;
import com.serviceprovider.business.module.admin.transaction.valueobjects.TransactionCSV;
import com.serviceprovider.business.module.admin.transaction.valueobjects.TransactionCSVError;
import com.serviceprovider.business.utility.RequestConstants;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

//~--- JDK imports ------------------------------------------------------------

import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * The Class TransactionCSVDataViewController.
 *
 * @author mrduongnv@gmail.com
 */
@Controller
public class TransactionCSVDataEditController {

    /** The Constant MIX_LIST. */
    private static final String MIX_LIST = "mixList";

    /** The Constant SUCCESS_LIST. */
    private static final String SUCCESS_LIST = "successList";

    /** The logger. */
    private final Logger logger = Logger.getLogger(getClass());

    /** The transaction import data service. */
    @Autowired
    private ITransactionImportDataService transactionImportDataService;

    /** The validation service. */
    @Autowired
    private IValidationService validationService;

    @ModelAttribute
    @RequestMapping(
        value  = RequestConstants.TransactionRequests.EDIT_TRANSACTIONCSV_RECORD,
        method = RequestMethod.GET
    )
    public ModelAndView showForm(HttpServletRequest request) {
        final String recordId = request.getParameter("record_id");

        if (StringUtils.isEmpty(recordId) ||!StringUtils.isAllDigits(recordId)) {
            return new ModelAndView(RequestConstants.TransactionRequests.TRANSACTION_SUMMARY_VIEW);
        }

        NewCsvReplica transactions = this.transactionImportDataService.retrieveTransactionCSV(recordId);

        if (transactions == null) {
            return new ModelAndView(RequestConstants.TransactionRequests.TRANSACTION_SUMMARY_VIEW);
        }

        ModelAndView modelAndView =
            new ModelAndView(RequestConstants.TransactionRequests.VIEW_EDIT_TRANSACTIONCSV_RECORD);

        modelAndView.addObject(transactions);

        return modelAndView;
    }

    /**
     * Show list.
     *
     * @param request
     *            the request
     * @return the model and view
     */
    @RequestMapping(
        value  = RequestConstants.TransactionRequests.EDIT_TRANSACTIONCSV_RECORD,
        method = RequestMethod.POST
    )
    public ModelAndView onSubmit(NewCsvReplica csv, BindingResult errors, HttpServletRequest request) {
        if (csv == null) {
            return new ModelAndView(RequestConstants.TransactionRequests.TRANSACTION_SUMMARY_VIEW);
        }

        ModelAndView mov = new ModelAndView(RequestConstants.TransactionRequests.VIEW_EDIT_TRANSACTIONCSV_RECORD);

        if (request.getParameter("cancel") != null) {
            return new ModelAndView("redirect:" + RequestConstants.TransactionRequests.EDIT_TRANSACTIONCSV_RECORD);
        }

        try {
            final TransactionCSVError csvError = null;    // validateTransactionCSV(csv);

            if (csvError != null) {
                final List<String> fields = csvError.getFields();

                for (String string : fields) {
                    errors.rejectValue(string, "edit.csv.".concat(string).concat(".not.valid"),
                                       StringUtils.makeFieldReadable(string).concat(" not valid."));
                }

                ModelAndView modelAndView =
                    new ModelAndView(RequestConstants.TransactionRequests.VIEW_EDIT_TRANSACTIONCSV_RECORD);

                modelAndView.addObject(csv);

                return modelAndView;
            }

            this.transactionImportDataService.updateTransaction(csv);
            mov.addObject("message",
                          "Transaction record with trace number " + csv.getTrace_number() + " updated successfully.");
            showRecords(mov, csv.getHistoryId());

            return mov;
        } catch (Exception e) {
            this.logger.error("Error occured when records are edited.", e);
            mov.addObject("message", "Error occured when records are edited.");
        }

        return mov;
    }

    /**
     * @param mov
     * @param integer
     */
    private void showRecords(ModelAndView mov, Integer fileId) {

        // if (fileId != null) {
        //
        // try {
        // final List<TransactionCSV> successList =
        // this.transactionImportDataService.retrieveImportedTransactionDataListByFileId(fileId,
        // Boolean.TRUE);
        // final List<TransactionCSV> mixList =
        // this.transactionImportDataService.retrieveImportedTransactionDataListByFileId(fileId,
        // Boolean.FALSE);
        //
        // mov.addObject(SUCCESS_LIST, successList);
        // mov.addObject(MIX_LIST, QueryUtils.prepairErrorList(mixList));
        //
        // } catch (Exception e) {
        // this.logger.error("Error occured when records are displayed.", e);
        // mov.addObject("message",
        // "Error occured when records are displayed.");
        // }
        // }
    }

    private TransactionCSVError validateTransactionCSV(TransactionCSV transactionCSV) {
        TransactionCSVError csvError = new TransactionCSVError();

        if (transactionCSV == null) {
            throw new IllegalArgumentException("CSV file reading failed.");
        }

        final String receiverAccount      = transactionCSV.getReceiverAccount();
        final String accountAlias         = transactionCSV.getAccountAlias();
        final String postingDate          = transactionCSV.getPostingDate();
        final String effectiveEntryDate   = transactionCSV.getEffectiveEntryDate();
        final String receiverName         = transactionCSV.getReceiverName();
        final String originatorName       = transactionCSV.getOriginatorName();
        final String identificationNumber =
            transactionCSV.getSsn().concat(" ").concat(transactionCSV.getOriginatorCode());

        transactionCSV.setIdentificationNumber(identificationNumber);

        final String credit                 = transactionCSV.getCredit();
        final String debit                  = transactionCSV.getDebit();
        final String transType              = transactionCSV.getTransType();
        final String standardEntryClassCode = transactionCSV.getStandardEntryClassCode();

        // this.validationService.checkForDigit(transactionCSV, csvError,
        // receiverAccount, "receiverAccount");
        // this.validationService.checkForString(transactionCSV, csvError,
        // accountAlias, "accountAlias");
        // this.validationService.checkForValidDate(transactionCSV, csvError,
        // postingDate, "MM/dd/yy hh:mm a", "postingDate");
        // this.validationService.checkForValidDate(transactionCSV, csvError,
        // effectiveEntryDate, "MM/dd/yy", "effectiveEntryDate");
        // this.validationService.checkForString(transactionCSV, csvError,
        // receiverName, "receiverName");
        // this.validationService.checkForString(transactionCSV, csvError,
        // originatorName, "originatorName");
        // this.validationService.checkIdentificationNumber(transactionCSV,
        // csvError, identificationNumber);
        // this.validationService.checkForCreditOrDebit(transactionCSV,
        // csvError, credit, "credit");
        // this.validationService.checkForCreditOrDebit(transactionCSV,
        // csvError, debit, "debit");
        // this.validationService.checkForString(transactionCSV, csvError,
        // transType, "transType");
        // this.validationService.checkForString(transactionCSV, csvError,
        // standardEntryClassCode, "standardEntryClassCode");
        //
        // if (csvError.getTransactionCSV() != null) {
        // return csvError;
        // }
        return null;
    }
}



